const TokenKey = 'token'
const UserKey = 'user'
// 非H5端模拟会话存储的前缀（用于区分持久化存储）
const SESSION_PREFIX = '__session__';

// -------------------------- Token 会话存储管理 --------------------------
export function getStorageToken() {
  // H5端使用原生sessionStorage
  if (process.env.VUE_APP_PLATFORM === 'h5') {
    return window.sessionStorage.getItem(TokenKey);
  }
  // 非H5端读取带会话前缀的存储
  return uni.getStorageSync(`${SESSION_PREFIX}${TokenKey}`);
}

export function setStorageToken(token) {
  if (process.env.VUE_APP_PLATFORM === 'h5') {
    return window.sessionStorage.setItem(TokenKey, token);
  }
  return uni.setStorageSync(`${SESSION_PREFIX}${TokenKey}`, token);
}

export function removeStorageToken() {
  if (process.env.VUE_APP_PLATFORM === 'h5') {
    return window.sessionStorage.removeItem(TokenKey);
  }
  return uni.removeStorageSync(`${SESSION_PREFIX}${TokenKey}`);
}

// -------------------------- 用户信息会话存储管理 --------------------------
export function getStorageUser() {
  let user;
  if (process.env.VUE_APP_PLATFORM === 'h5') {
    user = window.sessionStorage.getItem(UserKey);
  } else {
    user = uni.getStorageSync(`${SESSION_PREFIX}${UserKey}`);
  }
  return user ? JSON.parse(user) : {};
}

export function setStorageUser(user) {
  const userStr = JSON.stringify(user);
  if (process.env.VUE_APP_PLATFORM === 'h5') {
    return window.sessionStorage.setItem(UserKey, userStr);
  }
  return uni.setStorageSync(`${SESSION_PREFIX}${UserKey}`, userStr);
}

export function removeStorageUser() {
  if (process.env.VUE_APP_PLATFORM === 'h5') {
    return window.sessionStorage.removeItem(UserKey);
  }
  return uni.removeStorageSync(`${SESSION_PREFIX}${UserKey}`);
}

// -------------------------- 新增：清空所有会话存储（非H5端专用） --------------------------
export function clearAllSessionStorage() {
  if (process.env.VUE_APP_PLATFORM !== 'h5') {
    const keys = uni.getStorageInfoSync().keys;
    keys.forEach(key => {
      if (key.startsWith(SESSION_PREFIX)) {
        uni.removeStorageSync(key);
      }
    });
  } else {
    window.sessionStorage.clear();
  }
}